# encoding: utf-8
class BugsController < ApplicationController
  before_filter :authenticate_user!
  before_filter :is_member_of_project?
  before_filter :get_project, :only => [:new, :edit, :create, :update]
  
  def index
    @bugs = Bug.where(:project_id => params[:project_id]).order("created_at desc")

    respond_to do |format|
      format.html
      format.xml  { render :xml => @bugs }
    end
  end

  def show
    @bug = Bug.find(params[:id])

    respond_to do |format|
      format.html
      format.xml  { render :xml => @bug }
    end
  end

  def new
    @bug = Bug.new

    respond_to do |format|
      format.html
      format.xml  { render :xml => @bug }
    end
  end

  def edit
    @bug = Bug.find(params[:id])
  end

  def create
    @bug = Bug.new(params[:bug])
    @bug.project_id = params[:project_id]
    @bug.author_id = current_user.id
    @bug.topic = Topic.new(:name => @bug.title, :description => @bug.description, :user_id => @bug.author_id, :project_id => params[:project_id])

    ActiveRecord::Base.transaction do
      respond_to do |format|
        if @bug.save
          flash[:notice] = t :bug_create_success, :scope => [:flash, :notice]
          format.html { redirect_to(project_bug_path(params[:project_id], @bug)) }
          format.xml  { render :xml => @bug, :status => :created, :location => @bug }
        else
          format.html { render :action => "new" }
          format.xml  { render :xml => @bug.errors, :status => :unprocessable_entity }
        end
      end
    end
  end

  def update
    @bug = Bug.find(params[:id])
    @topic = Topic.find(@bug.topic_id)
    
    ActiveRecord::Base.transaction do
      respond_to do |format|
        if @bug.update_attributes(params[:bug]) && @topic.update_attributes(:name => @bug.title, :description => @bug.description)
          flash[:notice] = t :bug_change_success, :scope => [:flash, :notice]
          format.html { redirect_to(project_bug_path(params[:project_id], @bug)) }
          format.xml  { head :ok }
        else
          format.html { render :action => "edit" }
          format.xml  { render :xml => @bug.errors, :status => :unprocessable_entity }
        end
      end
    end
  end
end
